import React from 'react';
import {inject,observer} from 'mobx-react';
import { Avatar, Flex, Icon, Tools, SwipeAction } from 'weaver-mobile';
const getLabel = Tools.getLabel;
const allStore =[
  'esearchStore',
]

@inject(...allStore)
@observer
export default class SearchList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      src: Tools.mobileDetect(),
    };
    this.resultListRef = React.createRef();
  }

  componentWillMount() {
  }
  componentDidMount() {
  }

  hrmClick = (id) => {
    const {src} = this.state;
    const { urlMapping } = this.props.esearchStore;
    let url = urlMapping && urlMapping['RSC'].split('{ID}');
    let URL = url[0] + id;
    if(urlMapping['RSC']) {
      if(src.isEmobile()) {
        if(window.em) {
          window.em.openLink({
            url:`${URL}`, // 要打开链接的地址
            openType: 2, // 打开方式 1:当前窗口 2:新窗口 3:系统默认浏览器
            sysId: window.localStorage.emobile_ec_id, // 集成系统ID
            corpId:'', // 企业corpid
            agentId:'', // 应用id
            success: function (res) {
            }
          });
        }
      }else{
        urlMapping ? window.open(
          `${URL}`,
        ):''
      }
    }
  }

  hrmList = (res) => {
    let field = [];
    let other = JSON.parse(res.other);
    field.push(
      <SwipeAction
        key={res.id}
        // style={{ backgroundColor: 'gray' }}
        autoClose
        right={[
          {
            text: 'short',
            onPress: () => {},
            style: { backgroundColor: '#ddd', color: 'white' },
          },
          {
            text: 'long text',
            onPress: () => {},
            style: { backgroundColor: '#F4333C', color: 'white' },
          },
        ]}
        onOpen={() => {}}
        onClose={() => {}}
      >
        <Flex className="search-list-hrm-container" wrap={JSON.stringify(res)} onClick={() => {this.hrmClick(res.id)}} key={res.id}>
            {/* wrap: 为了支持无侵入传参数 */}
            <div className='image'>
              {  res.id ? <Avatar userId={res.id} />
                : <Avatar name={res.simpleTitle} url={other['URL']} />
              }
            </div>
            <div className='describe'>
              <Flex justify="start">
                <Flex.Item className='highlight'>{res.simpleTitle}</Flex.Item>
                <Flex.Item>{other['JOBTITLENAME']}</Flex.Item>
              </Flex>
              <Flex justify="start">
                <Flex.Item>{other['SUBCOMP']}</Flex.Item>
                <Flex.Item>{other['DEPT']}</Flex.Item>
              </Flex>
            </div>
            <div className='arrow'>
              <Icon type='right' color='#868686' />
            </div>
        </Flex>
      </SwipeAction>
    )

    return field;
  }

  typeOnClick = (schema,id,extendsUrl, item) => {
    const { urlMapping } = this.props.esearchStore;
    const {src} = this.state;
    const other = item.other ? JSON.parse(item.other) : undefined;
    
    if(urlMapping[schema]) {
      let URL = urlMapping[schema].replace('{ID}',id)+extendsUrl;
      if(schema !== 'DOC' || (other !== undefined && other !== '' && schema === 'DOC')){
        if(item.url && item.url !== '') {
          URL = item.url;
        }
      } 
      if(src.isEmobile()) {
        if(window.em) {
            window.em.openLink({
              url:`${URL}`, // 要打开链接的地址
              openType: 2, // 打开方式 1:当前窗口 2:新窗口 3:系统默认浏览器
              sysId: window.localStorage.emobile_ec_id, // 集成系统ID
              corpId:'', // 企业corpid
              agentId:'', // 应用id
              success: function (res) {
              }
          });
        }
      }else{
          window.open(
            `${URL}`,
          )
      }
    }
  }

  typeList = (res) => {
    let field = [];
    let resTitle = res.title;
    let extendsUrl=res.extendsUrl?res.extendsUrl:'';
    let reg = /\(<img(.*?)\/>\)/;
    if(resTitle.search(reg) > -1) {
      let regex = (/\[(.*?)\]/).exec(resTitle);
      if(regex !== null && regex.length > 0) {
        resTitle = <span>{regex[0]}<Icon type={'enclosure' } color={'#4D7AD8'} style={{verticalAlign: 'middle', margin: '0 5px' }} size="xxs" />
          <span dangerouslySetInnerHTML = {{ __html: res.simpleTitle }}></span>
        </span>;
      }
    } else {
      resTitle = <span dangerouslySetInnerHTML = {{ __html: resTitle }}></span>
    }
    field.push(
      <Flex className='search-list-type-container' wrap={JSON.stringify(res)} key={res.id} onClick={() => {this.typeOnClick(res.schema, res.id,extendsUrl, res)}}>
         {/* wrap: 为了支持无侵入传参数 */}
        <div className='right'>
          <div className='search-list-type-container-title'>
            <div url={res.url} >{resTitle}</div>
          </div>
          {(res.content !== ''&&res.content !== ' ') && <div className='search-list-type-container-content'>
            <div dangerouslySetInnerHTML = {{ __html: res.content }}/>
          </div>}
          <div className='search-list-type-container-time'>
            <div>{res.description}</div>
          </div>
        </div>
        <div className='arrow'>
          <Icon type='right' color='#868686' />
        </div>
      </Flex>
    )
    return field;
  }

  getList = () => {
    const {searchList, searchResult, pageCount, pageindex, loading, searchStatus} = this.props.esearchStore;
    let fields = [];
    let field = [];
    let message = '';
    loading ? message = <Icon style={{marginTop: '10'}} type='loading'/> : '';
    if(searchResult === '') {
      searchList && searchList.map(res => {
        if(res.schema === 'RSC') {
          field.push(this.hrmList(res))
        }else{
          field.push(this.typeList(res))
        }
        return '';
      });
      if(parseInt(pageCount,10) === parseInt(pageindex,10) && !loading) {
        message = getLabel(390064,'没有更多啦');
      }
      field.push(
        <div className='get-more' key='getmore'>{message}</div>
      )
      fields.push(
        <div className='hrmList' key='hrmList'>{field}</div>
      )
    }else{
      !loading && fields.push(
        <div className='search-nodata' key='search-nodata'>
          <div className='icon-item'>
            {/* <Icon type='search' color='#fff' /> */}
            <img alt='' src={require('../util/img.png')}></img>
          </div>
          {/* <div className='remind'>{getLabel(558,'提示')}</div> */}
          {searchResult}
          {searchStatus === '-1' && getLabel('131448','查询超时，请联系管理员。')}
        </div>
      )
      loading && fields.push(
        <div className='search-nodata' key='search-nodata'>
          <div className='icon-item'>
            <Icon type='loading'/>
          </div>
        </div>
      )

    }
    return fields;
  }

      
  onscroll = (e) => {
    const { pageCount,pageindex,isSearchStart, onSearchClick, tabParams } = this.props.esearchStore;
    if(this.resultListRef && this.resultListRef.current) {
      let scrollHeight = this.resultListRef.current.scrollHeight;// 列表的高度
      let scrollTop = this.resultListRef.current.scrollTop; // 滚动的高度
      let offsetHeight = this.resultListRef.current.offsetHeight; // 窗口的高度
      if(scrollHeight - offsetHeight -20 < scrollTop) {
        if (!isSearchStart) return;
        let params = {
          pageIndex: parseInt(pageindex, 10) + 1,
          contentType: tabParams.key,
          pagesize: 20
        };
        if(parseInt(pageCount,10) > parseInt(pageindex,10)) {
          const { search } = this.props.location;
          onSearchClick('scroll', params, this.props.history, search);
        }
      }
    }
  }

  render() {
    return(
      <div className='esearch-list-container' ref={this.resultListRef} style={{ height: this.props.height || '100%'}}
        onScroll={this.onscroll}
      >
        {
          this.getList()
        }
      </div>
    );
  }
}